package com.ychen.ruijee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ychen.ruijee.bean.AddressBook;
import com.ychen.ruijee.common.BaseContext;
import com.ychen.ruijee.dao.AddressBookDao;
import com.ychen.ruijee.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ychen@gotop.cn
 * @date 2024-06-07 15:59
 */
@Slf4j
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookDao, AddressBook> implements AddressBookService {
    /**
     * 查询该账号下的全部 收货地址
     * @param addressBook
     * @return
     */
    @Override
    public List<AddressBook> listAddressBook(AddressBook addressBook) {
        // 从 ThreadLocal 中获取到当前的登录 id
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("当前的 addressbook 对象为 ：{}",addressBook.toString());
        // 查询
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(addressBook.getUserId() != null,AddressBook::getUserId,addressBook.getUserId());
        wrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = this.list(wrapper);

        return list;
    }

    /**
     * 新增 收货地址
     *
     * @param addressBook
     * @return
     */
    @Override
    public boolean saveAddressBook(AddressBook addressBook) {
        log.info("【新增收货地址中：addressBook is {}】",addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        return this.save(addressBook);
    }

    /**
     * 收货信息 修改
     *
     * @param addressBook
     * @return
     */
    @Override
    public boolean updateAddressBook(AddressBook addressBook) {
        log.info("要修改的收货信息为：{}",addressBook.toString());
        AddressBook newAddressBook = new AddressBook();
        // 先去数据库中查询
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        Long loginId = BaseContext.getCurrentId();
        wrapper.eq(addressBook.getDetail()!= null,AddressBook::getUserId,loginId);
        AddressBook one = this.getOne(wrapper);
        log.info("【数据库中】要修改的收货信息：{}",one.toString());
        // 属性赋值
        newAddressBook.setId(one.getId());
        newAddressBook.setUserId(one.getUserId());
        newAddressBook.setConsignee(addressBook.getConsignee());
        newAddressBook.setDetail(addressBook.getDetail());
        newAddressBook.setLabel(addressBook.getLabel());
        newAddressBook.setPhone(addressBook.getPhone());
        newAddressBook.setSex(addressBook.getSex());
        log.info("【newAddressBook】要修改的收货信息：{}",newAddressBook.toString());
        return this.updateById(newAddressBook);
    }
}
